package ne.aishuyuan.video.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import ne.aishuyuan.video.bean.Media;
import ne.aishuyuan.video.bean.NetworkMedia;
import ne.aishuyuan.video.bean.PlayMedia;
import ne.aishuyuan.video.config.DownloadConfig;
import ne.aishuyuan.video.utils.DownloadUtil;
import ne.aishuyuan.video.utils.RestTemplateUtil;
import net.aishuyuan.api.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName: LoadResourceService
 * @Description: 加载资源服务
 * @Author: clj
 * @Date: 2021/11/2 16:09
 */
@Component
@Slf4j
public class LoadResourceService {
    @Autowired
    private DownloadConfig downloadConfig;
    @Autowired
    private RestTemplate restTemplate;

    /** 加载资源
     * @return void
     */
    public NetworkMedia loadMedia(JComboBox<Media> mediaList,JComboBox<Media> fixedMediaList,JComboBox<Media> timerMediaList) {
        PlayMedia playMedia = null,fixedPlayMedia = null,timerPlayMedia = null;
        Result<List<PlayMedia>> playMediaResult;
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("serialNumber", "PF1SLEMF");
        ResponseEntity<String> responseEntity = RestTemplateUtil.sendFormPostEntity(downloadConfig.getUrl(), HttpMethod.GET,paramMap,restTemplate);
        log.debug(">>>>>>>>>>>>>加载网络资源 = {}",responseEntity.getBody());
        playMediaResult = JSON.parseObject(responseEntity.getBody(),new TypeReference<Result<List<PlayMedia>>>(){});
        List<PlayMedia> playMediaList = playMediaResult.getData();

        //本地json文件获取
/*      ClassPathResource classPathResource = new ClassPathResource("resource.json");
        String showList = "";
        try {
            byte[]  bytes= FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
            showList = new String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Result<List<PlayMedia>> playMediaResult = JSON.parseObject(showList,new TypeReference<Result<List<PlayMedia>>>(){});
        List<PlayMedia> playMediaList = playMediaResult.getData();*/

        fixedPlayMedia = playMediaList.stream().filter(item ->  item.getPlayRule().equals("COMMON")).collect(Collectors.toList()).get(0);
        if (playMediaList.size() > 1) {
            timerPlayMedia =  playMediaList.stream().filter(item ->  item.getPlayRule().equals("TIMING")).collect(Collectors.toList()).get(0);
        }
        //根据当前时间来判断播放清单
        playMedia = fixedPlayMedia;
        if ( null != timerPlayMedia) {
            LocalDateTime startTime = timerPlayMedia.getPlayStartTime();
            LocalDateTime endTime = timerPlayMedia.getPlayEndTime();
            LocalDateTime now = LocalDateTime.now();
            if (now.isAfter(startTime) && now.isBefore(endTime)) {
                playMedia = timerPlayMedia;
            }
        }
        //下载，并将播放列表指向临时下载目录
        download(playMedia,fixedPlayMedia,timerPlayMedia,mediaList);
        log.debug(">>>>>>>>>>>>>更新播放列表本地文件为临时下载目录");
        //拷贝临时目录到正式播放目录，并更改播放列表指向为正式播放目录
        changePlayPath(mediaList,playMedia);
        NetworkMedia networkMedia = new NetworkMedia(playMedia,fixedPlayMedia,timerPlayMedia);
        setMediaList(fixedPlayMedia,timerPlayMedia,fixedMediaList,timerMediaList);
        return  networkMedia;
    }

    /**
     * 设置固定，定时播放列表数据
     * @param [fixedPlayMedia, timerPlayMedia, fixedMediaList, timerMediaList]
     * @return void
     */
    private void setMediaList(PlayMedia fixedPlayMedia,PlayMedia timerPlayMedia ,JComboBox<Media> fixedMediaList, JComboBox<Media> timerMediaList) {
        changeMediaList(fixedPlayMedia,fixedMediaList);
        if (null != timerPlayMedia && timerPlayMedia.getResourceVos().size() > 0 ) {
            changeMediaList(timerPlayMedia,timerMediaList);
        }
    }
    /**
     * 媒体下载
     * @param [playMedia]
     * @return void
     */
    private void download(PlayMedia playMedia,PlayMedia fixedPlayMedia, PlayMedia timerPlayMedia,JComboBox<Media> mediaList) {
        //下载前清空临时目录
        File tempFileDir = new File(downloadConfig.getTempPath());
        if (tempFileDir.exists()) {
            File[] files  = tempFileDir.listFiles();
            for (int i=0; i< files.length; i++) {
                File file = files[i];
                file.delete();
            }
        }
        if (!CollectionUtils.isEmpty(fixedPlayMedia.getResourceVos())) {
            download(fixedPlayMedia);
        }
        if (null != timerPlayMedia && !CollectionUtils.isEmpty(timerPlayMedia.getResourceVos())) {
            download(timerPlayMedia);
        }
        changeMediaList(playMedia,mediaList);
    }

    /**
     * 更改播放列表数据
     * @param [playMedia, mediaList, path]
     * @return void
     */
    private void changeMediaList(PlayMedia playMedia,JComboBox<Media> mediaList) {
        mediaList.removeAllItems();
        for (int i = 0; i < playMedia.getResourceVos().size(); i++) {
            Media media = playMedia.getResourceVos().get(i);
            //本地播放
            if (playMedia.getType().equals("LOCAL_PLAY") ) {
                media.setPath(downloadConfig.getTempPath());
            }
            media.setPlayType(playMedia.getType());
            mediaList.addItem(media);
        }
    }

    private void  download(PlayMedia currentPlayMedia) {
        for (int i = 0; i < currentPlayMedia.getResourceVos().size(); i++) {
            //离线，开启下载
            if (currentPlayMedia.getType().equals("LOCAL_PLAY")) {
                Media media = currentPlayMedia.getResourceVos().get(i);
                String url = media.getUrl();
                String filename = url.substring(url.lastIndexOf("/"));
                DownloadUtil.downloadUrl(url, downloadConfig.getTempPath() + File.separator + filename);
            }
        }
    }

    /**
     * 	更新播放目录
     * @param []
     * @return void
     */
    private void changePlayPath(JComboBox<Media> mediaList,PlayMedia playMedia) {
        new Thread(() -> {
            File  playFilePath = new File(downloadConfig.getPlayPath());
            if (!playFilePath.exists()) {
                playFilePath.mkdir();
            }
            File[] playFiles = playFilePath.listFiles();
            for (int i= 0;i <playFiles.length ;i++) {
                playFiles[i].delete();
            }
            //copy file
            File tempFilePath = new File(downloadConfig.getTempPath());
            if (tempFilePath.exists()) {
                File[] files = tempFilePath.listFiles();
                for (int i=0 ;i< files.length; i++) {
                    File file = files[i];
                    String filename = file.getName();
                    try {
                        FileUtils.copyFile(files[i],new File(playFilePath + File.separator + filename));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //更新播放列表本地清单路径为播放目录
            log.debug(">>>>>>>>>>>>>更新播放列表本地文件为播放目录");
            changeMediaList(playMedia,mediaList);
        }).start();
    }

}
